<?php

namespace app\api\service;

use think\facade\Cache;
use app\model\User;
use app\common\Common;
use app\model\Link;
use app\model\UserLoginRecord;

class FastAppService
{
    private $model;

    public function __construct(User $model, Link $linkModel, UserLoginRecord $userLoginRecordModel)
    {
        $this->model = $model;
        $this->linkModel = $linkModel;
        $this->userLoginRecordModel = $userLoginRecordModel;
    }

    // 用户登录
    public function userLogin($params)
    {
        $userInfo = $this->model->getDataByWhere(['device_id' => $params['device_id']], 'id, sign_time, user_name, avatar, link_id');

        if ($userInfo) {
            $saveData = [
                'id' => $userInfo['id'],
                'updated_at' => time()
            ];
        } else {
            $saveData = [
                'platform' => 4,
                'register_date' => date('Ymd'),
                'device_id' => $params['device_id'],
                'created_at' => time()
            ];
        }

        $saveData['last_login_time'] = time();
        $saveData['mobile_system'] = $params['mobile_system'];

        if (!empty($params['link_id'])) {
            $saveData['link_id'] = $params['link_id'];
            $saveData['activation_time'] = time();

            $userInfo['link_id'] = $params['link_id'];
        }

        // 
        $uid = $this->model->edit($saveData);

        if (!$uid) {
            return [];
        }

        $data = [];
        // 判断今天是否已签到
        if (!empty($userInfo['sign_time'])) {
            $currentSignTime = strtotime(date('Y-m-d', time()));
            $lastSignTime = strtotime(date('Y-m-d', $userInfo['sign_time']));
            if ($currentSignTime == $lastSignTime) {
                $data['sign_status'] = 1;
            } else {
                $data['sign_status'] = 0;
            }
        } else {
            $data['sign_status'] = 0;
        }

        $token = Common::createToken($uid);
        $data['token'] = $token;
        $data['id'] = $uid;
        $data['user_name'] = !empty($userInfo['user_name']) ? $userInfo['user_name'] : '';
        $data['avatar'] = !empty($userInfo['avatar']) ? $userInfo['avatar'] : '';

        $redis = Cache::store('redis')->handler();
        $key = config('redis_key.api.user_login');
        $expire = config('redis_key.api.user_login_expire');

        $redis->select(8);

        $boolUserId = $redis->set($token, $uid, $expire);
        if (!empty($params['link_id'])) {
            $linkIdKey = config('redis_key.api.user_login_link_id');
            $redis->set($linkIdKey . $token, $params['link_id'], $expire);
        }
        $boolUser = $redis->set($key . $uid, json_encode($data), $expire);

        return $data;
    }
}